package vashion.azeroth.common.net;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

public class IpUtil {
	
	private final static String PROXY_FLAG="X-Forwarded-For";

    @SuppressWarnings("unchecked")
	public static String getIpAddress(HttpServletRequest request) {
            String ip="";
    		Enumeration enumeration = request.getHeaderNames();
    		while(enumeration.hasMoreElements()){
    			String paraName=(String)enumeration.nextElement();
    			if(PROXY_FLAG.equalsIgnoreCase(paraName)){
    				ip=request.getHeader(paraName);
    				break;
    			}
    		}
            String localIP = "127.0.0.1";
            if ((ip == null) || (ip.length() == 0) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("Proxy-Client-IP");
            }
            if ((ip == null) || (ip.length() == 0) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if ((ip == null) || (ip.length() == 0) || (ip.equalsIgnoreCase(localIP)) || "unknown".equalsIgnoreCase(ip)) {
                    ip = request.getRemoteAddr();
            }
            if(ip.indexOf(",")!=-1)
            	ip = ip.split(",")[0];
            return ip;
    }
}
